from flask import Blueprint,request,jsonify
import json
from conf.comm import sqlalchemy_context
from database import * 

bp_course = Blueprint('course',__name__)
  

def xtree(data):
    tree = {}
    list = []
    if data:
        # 解析成字典
        for i in data:
            tree[i['id']]=i

        for j in data:
            # 判断是否有父类，0代表没有父类，直接加入列表
            if j['parent']==0:
                list.append(j)
            else:
                # 有父类
                # 看一下父类下是否有子类，有直接append
                if 'son' not in tree[j['parent']]:
                    tree[j['parent']]['son']=[]
                # 把子类加到特定的父类下
                tree[j['parent']]['son'].append(j)
                
        return list 
                
    else:
        return data


@bp_course.route('/cateM',methods=['POST','GET'])
@sqlalchemy_context()
def cateM():
    if request.method == 'POST':
        try:
            data = request.data
            if data:
                data = json.loads(data)
            else:
                data = request.form

            cate = Cate(name=data['name'],level=data['level'],parent=data['parent'],params=data['params'])
            db.session.add(cate)
            db.session.commit()
            return jsonify({'code':200}) 
        except :
            return jsonify({'code':20010})

    else:
        list = []
        cates = Cate.query.all()
        if cates:
            for i in cates:
                dict={'id':i.id,'name':i.name,'parent':i.parent,'params':i.params,'level':i.level}
                list.append(dict)
        list1 = xtree(list)
        return jsonify({'code':200,'list':list1})

           